# @Time : 2020/9/9 15:12
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np

targetColor = cv.imread("test1.bmp")
targetGray = cv.cvtColor(targetColor, cv.COLOR_BGR2GRAY)
targetClone = targetGray.copy()

template = cv.imread("target1.bmp", cv.IMREAD_GRAYSCALE)

# 1. 获取模板图片的宽高尺寸
temHeight, temWidth = template.shape
print(temWidth, temHeight)

# 执行模板匹配
result = cv.matchTemplate(targetGray, template, cv.TM_CCOEFF_NORMED)
minVal, maxVal, minLoc, (x, y) = cv.minMaxLoc(result)
cv.rectangle(targetGray, (x, y), (x + temWidth, y + temHeight), 0, 2)
cv.imshow("TargetRectangle", targetGray)

# 将图抠出来
resRect = targetClone[y:y + temHeight, x:x + temWidth]
print("resRect shape = {}".format(resRect.shape))
cv.imshow("TemplateRect", resRect)
cv.waitKey(0)
centerX, centerY = int(x + temWidth/2), int(y + temHeight/2)

# 然后对这个找到的图,寻找它的靶标位置.找到内圆的中心点坐标
# resBlurred = cv.medianBlur(resRect, 5)
# T, threshold = cv.threshold(resBlurred, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
#
# cv.imshow("threshold", threshold)
# cv.waitKey(0)
#
# kernel = (5, 5)
# erosion = cv.erode(threshold, kernel, iterations=1)
# dilation = cv.dilate(erosion, kernel, iterations=1)
# cv.imshow("Dilation", dilation)
# cv.waitKey(0)
#
# canny = cv.Canny(dilation, 30, 100)
# cv.imshow("Canny", canny)
# cv.waitKey(0)
#
# # 下面进行找圆心
# circles = cv.HoughCircles(canny, cv.HOUGH_GRADIENT, 1, 80, param1=100, param2=20, minRadius=2, maxRadius=10)
# p = circles[0][0]
#
# centerX, centerY = p[:2]
# centerX = int(centerX + x)
# centerY = int(centerY + y)
# 圆心坐标
cv.circle(targetColor, (centerX, centerY), 2, (0, 255, 0), -1)
cv.imshow("TargetColor", targetColor)
cv.waitKey(0)
